package mn.idax.exchange.otc.common.mq.producer;

import mn.idax.exchange.otc.util.LogUtils;
import org.apache.activemq.ScheduledMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;

import javax.jms.*;

/**
 * @Auther: dison
 * @Date: 2018/9/10 13:47
 * @Description: 延迟消息推送（订单过期等）
 *      步骤一：
 *          需在ActiveMQ配置，在如window目录：apache-activemq-5.10.0\conf\activemq.xml，在文件中添加 schedulerSupport为true
 *      <broker xmlns="http://activemq.apache.org/schema/core" brokerName="localhost" dataDirectory="${activemq.data}" schedulerSupport="true">
 *
 *      步骤二:
 *          代码中实现延迟投递消息，具体demo说明如下：
 *          textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);  延迟投递时间
 *          textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, period); 间隔时间
 *          textMessage.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, repeat);  重复投递次数
 *
 *       注意：
 *         ActiveMQ有延迟投递、定时投递等多种投递方式，可用于动态定时任务执行，但需主要以下几点
 *              1、MQ消息丢失问题。建议另起任务做补充操作
 *              2、重复消费风险。如一个topic被多个程序或集群订阅可能存在多次消费的可能
 *              3、延迟投递消息取消。因业务需要可能会存在延迟或定时投递消息取消
 */
@Component
public class DelayProducer {

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    public void delaySendMessage(String topic ,String message ,Long delayTimestamp){
        //获取连接工厂
        ConnectionFactory connectionFactory = this.jmsMessagingTemplate.getConnectionFactory();
        try {
            //获取连接
            Connection connection = connectionFactory.createConnection();
            connection.start();
            //获取session
            Session session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            // 创建一个消息队列
            Destination destination = session.createQueue(topic);
            MessageProducer producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            TextMessage textMessage = session.createTextMessage(message);
            //设置延迟时间
            textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delayTimestamp);
            long delay = 30 * 1000;
            long period = 10 * 1000;
            int repeat = 9;
            textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_DELAY, delay);
            textMessage.setLongProperty(ScheduledMessage.AMQ_SCHEDULED_PERIOD, period);
            textMessage.setIntProperty(ScheduledMessage.AMQ_SCHEDULED_REPEAT, repeat);
            //发送
            producer.send(textMessage);
            session.commit();
            producer.close();
            session.close();
            connection.close();
        } catch (Exception e) {
            LogUtils.error(this.getClass(), "--------ActiveMQ Dealy send error--------->" , e);
        }
    }

}
